package com.mlnx.netty.app.ecg.session.core;

import com.mlnx.common.utils.MyLog;
import com.mlnx.netty.app.config.BrokerConfig;

import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;

/**
 * Created by amanda.shan on 2019/8/15.
 */
public abstract class SessionManagerAbstract implements SessionManager {

    protected MyLog log = MyLog.getLog(getClass());

    public SessionManagerAbstract() {

        Thread thread = new Thread(getName()+" 检测session超时任务") {

            @Override
            public void run() {

                while (true) {
                    int second = BrokerConfig.READER_IDLE_MIN_TIME_SECONDES;
                    try {
                        second = refreshSessions();
                    }catch (Exception e){
                        log.error(e, e.getMessage());
                    }


                    try {
                        Thread.sleep(second * 1000);
                    } catch (InterruptedException e) {
                        log.error(e, e.getMessage());
                    }
                }
            }
        };

        thread.start();

    }

    public int refreshSessions() {

        int sleepTime = BrokerConfig.READER_IDLE_MAX_TIME_SECONDES;

        ConcurrentHashMap<String, Session> sessionClientIdMap = getSessionClientIdMap();

        ConcurrentHashMap<Channel, Session> sessionChannelMap = getSessionChannelMap();

        for (Channel channel : getSessionChannelMap().keySet()) {
            Session session = sessionChannelMap.get(channel);
            long newTime = System.currentTimeMillis();

            int second = (int) ((newTime - session.getLastPacketTime().getTime()) / 1000);

            // 超时
            if (second >= session.getKeepAliveSeconds()) {

                log.info("session {} 超时", session);
                removeSession(session);
            }

            if (second < sleepTime) {

                sleepTime = second;
            }
        }

        if (sleepTime < BrokerConfig.READER_IDLE_MIN_TIME_SECONDES) {

            sleepTime = BrokerConfig.READER_IDLE_MIN_TIME_SECONDES;
        }

        return sleepTime;
    }

}
